package com.mingqijia.gassafety.webserver.webSocket;

import com.alibaba.fastjson.JSONObject;
import com.mingqijia.gassafety.db.entity.Organization;
import com.mingqijia.gassafety.db.mapper.DeviceStateMapper;
import com.mingqijia.gassafety.webserver.service.OrganizationService;
import com.mingqijia.gassafety.webserver.utils.ApplicationContextUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName SubscriptionConfig.java
 * @createTime 2022年06月23日
 */
@Component
@Slf4j
public class WebSocketMessageListener implements MessageListener {

    private static final String split = ";;";

    @Autowired
    private OrganizationService organizationService;

    /**
     * 消息监听
     *
     * @param message
     * @param pattern
     */
    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("WebSocketMessageListener:监听到redis消息：{}", message);
        byte[] body = message.getBody();
        if (body.length > 0) {
            String mess = new String(message.getBody(), StandardCharsets.UTF_8).trim().replaceAll("\\\\", "");
            if (mess.length() >= 2) mess = mess.substring(1, mess.length() - 1);
            // 发送消息
            String spId = "";
            if (mess.contains(split)) {
                String[] split = mess.split(WebSocketMessageListener.split);
                mess = split[0];
                spId = split[1];
            }
            if (organizationService==null){
                organizationService = ApplicationContextUtils.getBean(OrganizationService.class);
            }
            List<Organization> organizations = organizationService.getParentIdBySpid(spId);
            log.info("onMessage-organizations:{}", JSONObject.toJSONString(organizations));
            WebSocketProcess.sendMessage(spId, mess,organizations);
        }
    }


}
